#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/26 0:21
# @Author  : huidong.bai
# @File    : audio_controller.py
# @Software: PyCharm

import os
import pygame
import time
import pyaudio
import wave
import threading

chunk = 1024  # Record in chunks of 1024 samples
sample_format = pyaudio.paInt16  # 16 bits per sample
channels = 2
fs = 44100  # Record at 44100 samples per second

# Create an interface to PortAudio


def play_query(wake_audio, audio):
    wake_up(wake_audio)
    pygame.mixer.init()
    pygame.mixer.pre_init(16000, -16, 2, 2048)
    pygame.mixer.init()
    pygame.mixer.music.load(audio)
    pygame.mixer.music.play()
    time.sleep(2)
    pygame.mixer.music.stop()


def wake_up(wake_audio):
    pygame.mixer.init()
    pygame.mixer.pre_init(16000, -16, 2, 2048)
    pygame.mixer.init()
    pygame.mixer.music.load(wake_audio)
    pygame.mixer.music.play()
    time.sleep(3)
    pygame.mixer.music.stop()


def record(seconds, filename):
    print('开始录制')
    p = pyaudio.PyAudio()
    stream = p.open(format=sample_format,
                    channels=channels,
                    rate=fs,
                    frames_per_buffer=chunk,
                    input_device_index=1,
                    input=True)

    # Initialize array to store frames
    frames = []

    # Store data in chunks for 3 seconds
    for i in range(0, int(fs / chunk * seconds)):
        data = stream.read(chunk)
        frames.append(data)

    # Stop and close the stream
    stream.stop_stream()
    stream.close()
    # Terminate the PortAudio interface
    p.terminate()
    print('停止录制')

    # Save the recorded data as a WAV file
    wf = wave.open(filename, 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(p.get_sample_size(sample_format))
    wf.setframerate(fs)
    wf.writeframes(b''.join(frames))
    wf.close()


def query_to_record(wake_audio, query, record_path, file_path):
    t_play = threading.Thread(target=play_query, args=(wake_audio, query,))
    t_play.start()
    record(9, record_path)
    audio_operation(record_path.split('\\')[2], 'myprofile', file_path)

    # 停止播放操作
    play_query(wake_audio, './停止播放.wav')
    time.sleep(3)


def audio_operation(audio_path, profile, file_path):
    cmd_audio_operation = f'cd {file_path} &' \
                          f'sox {audio_path} -n trim 2.0 3.3 noiseprof {profile} &' \
                          f'sox {audio_path} clean_{audio_path} noisered myprofile 0.21 &' \
                          f'sox clean_{audio_path} slice_{audio_path} trim 0.5 8.5 &' \
                          f'del {audio_path} &' \
                          f'del {profile} &' \
                          f'del clean_{audio_path} &' \
                          f'rename slice_{audio_path} {audio_path}'

    os.popen(cmd_audio_operation)


if __name__ == '__main__':
    record(10, 'noise.wav')
